<template>
  <div>
    <!-- banner区域 -->
    <div class="news-banner tac">
      <h2 class="c-fff fw400">橙券新闻动态</h2>
      <p class="fz20 c-fff">
        新闻动态抢先看，从能力输出到技术赋能，橙券从未放缓脚步，只为与您见证橙券成长的每一步！
      </p>
    </div>
    <div class="news-content bg-fc">
      <ul class="w1200 flex flex-wrap">
        <li v-for="item in newsList" :key="item._id">
          <a href="javascript:;" @click="handleJump(item)">
            <img :src="item.cover" width="386" height="219" alt="!" />
            <h4 class="news-title fz16 lh56 c-333 fw400 pl20">
              {{ item.title }}
            </h4>
            <span class="news-date fz14 lh50 c-666 pl20">{{
              item.updatedAt
            }}</span>
          </a>
        </li>
      </ul>

      <div class="page-sorter pos-rel tac">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :total="pagesData.total"
          :page-size.sync="pagesData.pageSize"
          :current-page="pagesData.pageNumber"
          @prev-click="handleClick"
          @next-click="handleClick"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import "@/assets/css/news.css";
import { mapActions } from "vuex";

export default {
  name: "News",

  data() {
    return {
      newsList: [],
      pagesData: {}, 
      // pageNumber--当前页数？ pageSize--每页展示的数据数 total--共有多少条数据
      pageSize: 3,
      newsListCach:[],
      pagesDataCach:[],
    };
  },
  mounted() {
    this.$EventBus.$emit("navActive", "news");
    this.getNewsList(1, this.pageSize);
  },
  methods: {
    ...mapActions("news", ["setTime"]),
    // 跳转详情页
    handleJump(item) {
      this.setTime(item.updatedAt);
      this.$router.push({ name: "details", params: { id: item._id } });
    },

    // 换页
    handleClick(nextPageNum) {
      this.getNewsList(nextPageNum, this.pageSize);
    },
    // 获取新闻列表
    async getNewsList(pageNumber, pageSize) {
      const isHad = this.newsListCach.some((item, idx)=>{
        // 如果有 更新newsList pagesData
        if(item.pageNumber === pageNumber){
          this.newsList = item.data
          this.pagesData = this.pagesDataCach.filter((item)=>{
            return item.pageNumber === pageNumber
          })[0]
        }
        return item.pageNumber === pageNumber
      })

      if(isHad) return 

      const res = await this.$api.getNewsList(pageNumber, pageSize);
      this.newsList = res.data;
      this.pagesData = res.pagination;
      this.newsListCach.push({
        data:res.data,
        pageNumber:res.pagination.pageNumber // 总数据数组的唯一标识
      })
      this.pagesDataCach.push(res.pagination)
      console.log("获取新闻列表", res);
    },
  },
};
</script>

<style lang="scss" scoped>
</style>